<template>
  <div>
    <!-- 搜索 -->
    <!-- 旧件回运 -->
    <TopFilter ref="TopFilterss" :list="topFilterInit" :cols="3" :collapse="collapse" labelWidth="110" @filterChange="changeHandle"></TopFilter>
    <!-- table -->
    <FilterTable ref="table" :columns="columns" :params="fetchParams" :dataSource="dataList" :datakey="'records'" :fetchapi="fetchApi" :onColumnsChange="columns => (this.columns = columns)" :onRowSelectChange="selectChange"  :is-select-column="true" :isServerFilter="false">

      <template slot="controls" slot-scope="props">
        <span :style="{ padding: '10px 20px',display:inline-block}" v-if="appId == 'beijing'"><multiuse-button size="small" type="primary"  :click="zctijiao.bind()">暂存重新提交</multiuse-button></span>
        <multiuse-button size="small" type="primary" icon="el-icon-plus" @click="add()">新增</multiuse-button>
        <multiuse-button type="primary" @click="exportFileBtn()">导出</multiuse-button>
<!--        <multiuse-button size="small" type="primary" :click="downloadTemplate.bind()">下载模版</multiuse-button>-->
<!--        <multiuse-button size="small" icon="el-icon-upload" :click="showImportFun">导入</multiuse-button>-->
      </template>
    </FilterTable>
    <Drawer :visible.sync="visibleEdit" :title="'旧件回运编辑'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditForm @close="closeEdit" @save="saveEdit" :rowData="returnId"></EditForm>
    </Drawer>
    <Drawer :visible.sync="visibleAdd" :title="'旧件回运新增'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <AddForm @close="closeAdd" @save="saveAdd"></AddForm>
    </Drawer>
    <Drawer :visible.sync="visibleEditBj" :title="'旧件回运编辑'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <EditFormBj @close="closeEdit" @save="saveEdit" :rowData="returnId"></EditFormBj>
    </Drawer>
    <Drawer :visible.sync="visibleAddBj" :title="'旧件回运新增'" destroyOnClose width="60%" :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}">
      <AddFormBj @close="closeAdd" @save="saveAdd"></AddFormBj>
    </Drawer>
    <BaseDialog :visible.sync="showImport" :closable="false" icon="el-icon-upload" title="导入" width="800px" destroyOnClose :containerStyle="{ height: 'calc(100% - 120px)', overflow: 'auto', paddingBottom: '60px' }">
      <importExcel @close="showImport = false" @importclose="editsave1()" url="/api/cms_claimdealer/rPReturn/importExcel"/>
    </BaseDialog>
  </div>
</template>
<script>
import moment from "moment";
import {
  getListByPage,
  getListForExport,
  downloadModel,
  piliangzctj,
  exporturl,
  getReturnListByPageNew,
  getListForExportNew
} from '@/api/usedPartsReturnManage/usedPartsReturn_DLR/usedPartsReturn';
import EditForm from './EditForm.vue';
import AddForm from './AddForm.vue';
import EditFormBj from './EditFormBj.vue';
import AddFormBj from './AddFormBj.vue';
import { exportExcelFile } from '@/utils/index';
import importExcel from '@/pages/claimDemage/tools/importExcel.vue';
import {  getAppId } from '@/assets/js/auth';
import {getListByExample, getPartType} from '@/api/dictionary/index.js';

export default {
  components: {
    EditForm,
    AddForm,
    EditFormBj,
    AddFormBj,
    importExcel
  },
  data() {
    return {
      dataList: [],
      visible: false,
      showImport: false,
      collapse: true,
      infoId: null,
      topFilterInit: this.topFilterInitFun(),
      flterValue: {}, //参数
      columns: this.creatHeader(),
      fetchApi: getListByPage,
      fetchParams: {
        returnStatus : '',
      }, //ipa 接口
      returnId: null,
      selectedRows: [], //选中服务站
      visibleEdit: false,
      visibleAdd: false,
      visibleAddBj: false,
      visibleEditBj: false,
      appId: null
    };
  },
  async created() {
    this.chuqi();
    this.chuqi2();
    // this.fetchParams.beginCreatedAt = moment().startOf('week').format('YYYY-MM-DD HH:mm:ss');
    // this.fetchParams.endCreatedAt = moment().endOf('week').format('YYYY-MM-DD HH:mm:ss');
    this.appId = await getAppId();
  },
  methods: {
    async chuqi() {
      //查询状态
      const res1 = await getPartType({ type: 5588 });
      this.topFilterInit.find(x => x.fieldName == 'returnStatus').initialValue = '';
      this.topFilterInit.find(x => x.fieldName == 'returnStatus').itemList = res1.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
    },
    async chuqi2() {
      //查询状态
      const res1 = await getPartType({ type: 5595 });
      this.topFilterInit.find(x => x.fieldName == 'returnType').initialValue = '';
      this.topFilterInit.find(x => x.fieldName == 'returnType').itemList = res1.data.map(y => ({ text: y.codeCnDesc, value: y.codeId }));
    },
  //暂存重新提交
    async zctijiao() {
      if (this.selectedRows.length > 0) {
        let str = '';
        this.selectedRows.map((x) => {
          str += x.returnId + ',';
        });
        const res = await piliangzctj({ ids: str, status: '55881002' });
        this.fetchParams = { ...this.fetchParams };
      } else {
        return this.$notify.warning({ title: '提示信息', message: '请勾选后再进行暂存重新提交！' });
      }
    },
    //选中
    selectChange(rows) {
      this.selectedRows = rows;
      console.log(this.selectedRows);
    },
    add() {
      // if (getAppId() == 'arcfox') {
        this.visibleAdd = true;
      // }else{
      //   this.visibleAddBj = true;
      // }
    },
    edit(val) {
      this.returnId = val;
      console.log("编辑ID",val)
      // if (getAppId() == 'arcfox') {
        this.visibleEdit = true;
      // }else{
      //   this.visibleEditBj = true;
      // }

    },
    closeEdit() {
      this.visibleEdit = false;
      this.visibleEditBj = false;
    },
    editsave1() {
      this.showImport = false;
      this.fetchParams = { ...this.fetchParams };
    },
    saveEdit() {
      this.visibleEdit = false;
      this.fetchParams = { ...this.fetchParams };
    },
    closeAdd() {
      this.visibleAdd = false;
      this.visibleAddBj = false;
    },
    saveAdd() {
      this.visibleAdd = false;
      this.fetchParams = { ...this.fetchParams };
    },
    close() {
      this.visible = false;
      this.fetchParams = { ...this.fetchParams };
    },
    //下载模板
    downloadTemplate() {
      this.$confirm('此操作将下载excel模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        downloadModel().then((res) => {
          console.log(res);
          exportExcelFile(res.data, '旧件回运导入模板');
        });
      });
    },
    showImportFun() {
      this.showImport = true;
    },
    //搜索获取数据
    changeHandle(val) {
      if(val.beginCreatedAt || val.endCreatedAt) {
        if (!val.beginCreatedAt) {
          this.$notify.warning({ title: '提示信息', message: '开始日期不可为空！' });
          return
        }
        if(!val.endCreatedAt) {
          this.$notify.warning({ title: '提示信息', message: '结束日期不可为空！' });
          return
        }
      }
      if(getAppId() == 'arcfox') {
        if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '日期跨度不可超过十二个月！' });
          return
        }
      } else {
        if (moment(moment(val.endCreatedAt).format('YYYY-MM-DD')).diff(moment(val.beginCreatedAt), 'months', true) > 12) {
          this.$notify.warning({ title: '提示信息', message: '日期跨度不可超过十二个月！' });
          return
        }
      }
      this.fetchParams = Object.assign({}, this.fetchParams, val);
      console.log(val);
    },
    // //旧件仓库下拉框
    // async chuqi() {
    //   console.log("===== 获取下拉框数据 ====== ")
    //   const res = await getListByExample();
    //   console.log("==========",res)
    //   if (res.resultCode == 200) {
    //     this.topFilterInit.find(x => x.fieldName == 'whCode').initialValue = '';
    //     this.topFilterInit.find(x => x.fieldName == 'whCode').itemList = res.data.map(y => ({ text: y.whName, value: y.whCode }));
    //   }
    // },
    // 导出
   async exportFileBtn() {
       try {
         // let params = { reportNo: "RE202103060001" }
         let params = {...this.fetchParams}
         let res = await getListForExportNew(params);
         exportExcelFile(res.data, '旧件回运列表')
       } catch (err) {
         console.warn(err)
       }
     // this.topFilterInit.map((x) =>{
     //   if (x.fieldName == 'returnNo') {
     //     this.fetchParams.returnNo = x.initialValue;
     //   }
     //   if (x.fieldName == 'whName') {
     //     this.fetchParams.whName = x.initialValue;
     //   }
     //   if (x.fieldName == 'beginCreatedAt|endCreatedAt') {
     //     x.beginCreatedAt = x.initialValue[0];
     //     x.endCreatedAt = x.initialValue[0];
     //   }
     //  }
     // )
     // console.log("fetchParams", this.fetchParams);
     // getListForExport(this.fetchParams)
      // let json = Object.assign({}, { CODE: 'CODE_00000222' }, this.fetchParams);
      // let res = await exporturl(json);
      // if (res.resultCode == 200) {
      //   this.$router.push('/admin/auth/oem/downloadCenter');
      // }
      // let beginSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
      // let endSubmitDate = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
      // if(!beginSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '回运单创建开始日期不可为空！' });
      //   return
      // }
      // if(!endSubmitDate) {
      //   this.$notify.warning({ title: '提示信息', message: '回运单创建结束日期不可为空！' });
      //   return
      // }
      // if(getAppId() == 'arcfox') {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '回运单创建日期跨度不可超过十二个月！' });
      //     return
      //   }
      // } else {
      //   if (moment(moment(endSubmitDate).format('YYYY-MM-DD')).diff(moment(beginSubmitDate), 'months', true) > 12) {
      //     this.$notify.warning({ title: '提示信息', message: '回运单创建日期跨度不可超过十二个月！' });
      //     return
      //   }
      // }
      // let obj = Object.assign({}, this.fetchParams, { returnStatusStrs : '55881001' ,xhrAbort: false});
      // obj.beginCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[0];
      // obj.endCreatedAt = this.topFilterInit.find(x => x.fieldName == "beginCreatedAt|endCreatedAt").initialValue[1];
      // console.log("=== 点击导出 ===")
      // getListForExport(Object.assign({whCode:this.topFilterInit.find(x => x.fieldName == 'whCode').initialValue}, obj)).then(res => {
      //   exportExcelFile(res.data, '旧件回运');
      // });
    },
    //搜索数据
    topFilterInitFun() {
      return [
        {
          type: 'INPUT',
          label: '通知单号',
          fieldName: 'returnNo',
          placeholder: '请输入通知单号...',
          initialValue: ''
        },
        // {
        //   type: 'INPUT',
        //   label: '回运仓库代码',
        //   fieldName: 'whCode',
        //   placeholder: '请输入回运仓库代码...',
        //   initialValue: '',
        // },
        {
          type: 'INPUT',
          label: '回运仓库名称',
          fieldName: 'whName',
          placeholder: '请输入回运仓库名称...',
          initialValue: '',
        },
        {
          type: 'RANGE_DATE',
          label: '回运日期',
          fieldName: 'beginCreatedAt|endCreatedAt',
          placeholder: '请输入',
          initialValue: '',
          //     [
          //       moment()
          //         .startOf('week')
          //         .format('YYYY-MM-DD HH:mm:ss'),
          //     moment()
          //     .endOf('week')
          //       .format('YYYY-MM-DD HH:mm:ss')
          //    ],
          // rules: [{ required: false, message: '请选择日期', trigger: 'change' }]
        },
        {
          type: 'RANGE_DATE',
          label: '发运日期',
          fieldName: 'beginDlDate|endDlDate',
          placeholder: '请输入',
          initialValue: ''
        },
        {
          type: 'SELECT',
          label: '状态',
          initialValue: '',
          fieldName: 'returnStatus',
          filterable: true,
          placeholder: '请选择...',
          itemList: []
        },
        {
          type: 'SELECT',
          label: '回运类型',
          initialValue: '',
          fieldName: 'returnType',
          filterable: true,
          placeholder: '请选择...',
          itemList: []
        }
      ];
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          fixed: 'left',
          sorter: true,
          render: (props) => {
            return <span>{props.row.index + 1}</span>;
          },
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 80,
          render: props => {
            return (
              <div style="text-align:center">
                <multiuse-button size="mini" type="text" onClick={() => this.edit(props.row.returnId)}>
                  编辑
                </multiuse-button>
              </div>
            );
          }
        },
        { title: '回运通知单号', dataIndex: 'returnNo', sorter: true },
        { title: '回运类型', dataIndex: 'returnTypeStr', sorter: true },
        { title: '回运仓库', dataIndex: 'whName', sorter: true },
        { title: '状态', dataIndex: 'statusStr', sorter: true },
        { title: '索赔单数', dataIndex: 'claimNum', sorter: true },
        { title: '旧件数量', dataIndex: 'partNum', sorter: true },
        { title: '发运时间', dataIndex: 'dlDate', sorter: true , dateFormat: 'YYYY-MM-DD'},
        { title: '回运单创建时间', dataIndex: 'createdAt', sorter: true}
      ];
    }
  }
};
</script>

<style lang="less" scoped></style>
